package com.loren.demo23.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

@Slf4j
public class AESUtils {

    private static final String KEY_ALGORITHM = "AES";

    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    private static final char[] BCD_LOOKUP = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String encrypt(String text, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = text.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            byte[] result = cipher.doFinal(byteContent);
            return bytesToHexStr(result);
        } catch (Exception e) {
            log.error("AES encrypt error", e);
        }
        throw new RuntimeException("AES encrypt error");
    }

    public static String decrypt(String text, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            byte[] result = cipher.doFinal(hexStrToBytes(text));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES decrypt error", e);
        }
        throw new RuntimeException("AES decrypt error");
    }

    private static SecretKeySpec getSecretKey(final String key) {
        KeyGenerator keyGenerator;
        try {
            keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, new SecureRandom(key.getBytes()));
            SecretKey secretKey = keyGenerator.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            log.error("AES generator key error", e);
        }
        throw new RuntimeException("AES generator key error");
    }

    private static String bytesToHexStr(byte[] bytes) {
        StringBuilder builder = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            builder.append(BCD_LOOKUP[(b >>> 4) & 0x0f]);
            builder.append(BCD_LOOKUP[b & 0x0f]);
        }
        return builder.toString();
    }

    private static byte[] hexStrToBytes(String hexStr) {
        byte[] bytes = new byte[hexStr.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            String substring = hexStr.substring(2 * i, 2 * i + 2);
            bytes[i] = (byte) Integer.parseInt(substring, 16);
        }
        return bytes;
    }
}
